<template>
    <div class="page flex-center">
        <div class="sign-box">
            <h1 class="title">{{ t('login') }}</h1>
            <el-form ref="formRef" :model="form" :rules="rules" label-width="86px">
                <el-form-item :label="t('form.username')" prop="account">
                    <el-input v-model="form.account" :placeholder="t('form.usernameHolder')" prefix-icon="user" />
                </el-form-item>
                <el-form-item :label="t('form.password')" prop="password">
                    <el-input v-model="form.password" type="password" :placeholder="t('form.passwordHolder')"
                        prefix-icon="lock" />
                </el-form-item>
                <el-form-item label>
                    <el-button type="primary" class="w100p" :loading="loading" @click="doLogin">{{
                        t('login')
                    }}</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>
  
<script setup>
import { login } from '@/apis/login'

const { t } = useI18n()
const router = useRouter()

const store = useStore()
console.log(store)

const formRef = ref()
const loading = ref(false)
// 定义登录表单
const form = reactive({
    account: 'admin',
    password: 'admin'
})

const rules = computed(() => {
    return {
        account: [
            {
                required: true,
                message: t('form.usernameHolder'),
                trigger: ['blur', 'change']
            },
            {
                pattern: /^[a-zA-Z][a-zA-Z0-9_-]{3,31}$/,
                message: t('form.usernameError'),
                trigger: ['blur', 'change']
            }
        ],
        password: [
            { required: true, min: 4, message: t('form.passwordError'), trigger: ['blur', 'change'] },
        ]
    }
})

const doLogin = () => {
    formRef.value.validate((valid) => {
        console.log('valid', valid)
        if (!valid) {
            return
        }
        // 执行登录接口的逻辑
        console.log('开始执行登录')
        // loading.value = true
        login(form)
            .then((res) => {
                console.log('登陆成功了')
                console.log('res====', res)
                store.commit('user/setToken', res.data.token)
                store.dispatch('user/refreshInfo')
                router.push('/')

                // 设置菜单路由为false
                store.commit('setRouteLoaded', false)
            })
            .finally(() => {
                loading.value = false
            })
    })
}
</script>
  
<style scoped lang="scss">
.page {
    height: 100%;
    // background: url(@/assets/bg.jpg) no-repeat;
    background-size: cover;
}

.sign-box {
    width: 400px;
    background: #fff;
    padding: 30px 50px 20px 30px;
    border-radius: 4px;
    box-shadow: 0 0 10px #022c44;
}

.title {
    text-align: center;
    font-size: 20px;
    line-height: 30px;
    margin-top: 0;
    margin-bottom: 10px;
    color: #000;
}
</style>